package com.xiaoyu.base;

import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;

import android.content.Context;

import androidx.annotation.NonNull;

import com.xiaoyu.base.dao.AreaDao;
import com.xiaoyu.base.dao.HotAreaDao;
import com.xiaoyu.base.dao.ProvinceCityDao;
import com.xiaoyu.base.entity.AreaEntity;
import com.xiaoyu.base.entity.HotAreaEntity;
import com.xiaoyu.base.entity.ProvinceCityEntity;

@Database(entities = {ProvinceCityEntity.class, AreaEntity.class, HotAreaEntity.class}, version = 1)
public abstract class GlobalDatabase extends RoomDatabase {

    private static final String TAG = "GlobalDatabase";
    private static final String DATABASE_NAME = "app_global_db";

    private static DatabaseEntry sDatabaseEntry;

    public abstract ProvinceCityDao provinceCityDao();

    public abstract AreaDao areaDao();

    public abstract HotAreaDao hotAreaDao();

    /**
     * @throws IllegalStateException if database not created
     */
    @NonNull
    public static GlobalDatabase getCurrentDatabase() {
        final GlobalDatabase.DatabaseEntry entry = sDatabaseEntry;
        if (entry == null) {
            throw new IllegalStateException("database not created");
        }
        return entry.database;
    }

    /**
     * @throws IllegalArgumentException if context is empty
     */
    public static void openDatabase(@NonNull Context context) {
        synchronized (GlobalDatabase.class) {
            if (sDatabaseEntry == null) {
                sDatabaseEntry = GlobalDatabase.DatabaseEntry.create(context);
            }
        }
    }

    public static void closeDatabase() {
        synchronized (GlobalDatabase.class) {
            if (sDatabaseEntry != null) {
                sDatabaseEntry.closeDatabase();
                sDatabaseEntry = null;
            }
        }
    }

    private static class DatabaseEntry {

        private final GlobalDatabase database;

        private static GlobalDatabase.DatabaseEntry create(@NonNull Context context) {
            GlobalDatabase database = Room.databaseBuilder(context.getApplicationContext(), GlobalDatabase.class, DATABASE_NAME)
                    .build();
            return new DatabaseEntry(database);
        }

        private DatabaseEntry(@NonNull GlobalDatabase database) {
            this.database = database;
        }

        private void closeDatabase() {
            database.close();
        }
    }
}
